<template>
  <div class="salarys-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane v-loading="loading" label="用户管理" name="role">
            <el-button type="primary" @click="showDia = true"
              >+新增角色</el-button
            >
            <el-table :data="list">
              <el-table-column
                label="序号"
                type="index"
                :index="typeIndex"
                width="120"
              />
              <el-table-column label="角色名称" prop="name" width="120" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <!-- <p>{{ row.id }}</p> -->
                  <el-button
                    type="primary"
                    size="mini"
                    @click="clickAssignPermissions(row.id)"
                    >分配权限</el-button
                  >
                  <el-button
                    type="success"
                    size="mini"
                    @click="clickShowDia(row.id)"
                    >编辑</el-button
                  >
                  <el-button type="danger" size="mini" @click="delTable(row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <!--
              @size-change="handleSizeChange" 每页条数发生变化时，触发事件
              @current-change="handleCurrentChange" 当前页变化时候，触发事件
             -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <el-dialog
              :title="diaTitle"
              :visible="showDia"
              @close="clickCloseDia"
            >
              <el-form
                ref="Form"
                :model="form"
                :rules="rulesForm"
                label-width="100px"
              >
                <el-form-item prop="name" label="角色名称">
                  <el-input v-model="form.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item prop="description" label="角色描述">
                  <el-input
                    v-model="form.description"
                    placeholder="请输入角色描述"
                  />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="clickCloseDia">取消</el-button>
                <el-button type="primary" @click="sumbitBtn">确定</el-button>
              </template>
            </el-dialog>
          </el-tab-pane>

          <el-tab-pane label="公司信息" name="set">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyData.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyData.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyData.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyData.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 分配权限Dia -->
      <el-dialog
        :title="DiaShowTitle"
        :visible="DiaShowDia"
        @close="closeShowDia"
      >
        <el-tree
          ref="tree"
          :data="permissionsData"
          :props="{ label: 'name' }"
          show-checkbox
          check-strictly
          default-expand-all
          node-key="id"
        >
        </el-tree>
        <template #footer>
          <el-button @click="closeShowDia">取消</el-button>
          <el-button type="primary" @click="clickAssignBtn">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 角色API
import {
  reqGetSole,
  reqGetDelRole,
  reqGetAddRoles,
  reqGetRoleId,
  reqGetUpdataRole,
} from '@/api/settings'
// 企业API
import { reqGetIdCompany } from '@/api/company'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
import { reqAssignPerm } from '@/api/setting'
export default {
  name: 'Setting',
  data() {
    return {
      list: [],
      page: 1,
      pagesize: 5, // 默认传入每页条数
      total: 0, // 默认总数
      activeName: 'role',
      loading: false, // 控制loading
      showDia: false, // 控制弹窗
      DiaShowTitle: '分配权限', // 分配dia标题
      DiaShowDia: false, // 分配dia显隐控制
      roleId: '', // 记录操作的id
      permissionsData: [], //权限数据存储(树形数据)
      form: {
        name: '',
        description: '',
      },
      rulesForm: {
        name: [
          {
            required: true,
            message: '输入不能为空！！！',
            trigger: ['blur', 'change'],
          },
        ],
        description: [
          {
            required: true,
            message: '输入不能为空！！！',
            trigger: ['blur', 'change'],
          },
        ],
      },
      companyData: {}, // 企业数据 原始数据存在vuex中
    }
  },
  // 计算属性控制共享弹窗标题
  computed: {
    // dia控制标题
    diaTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    },
  },
  created() {
    this.reqGetRoleList()
    this.getComanyInfo() // 查询到的企业
  },
  methods: {
    ...mapState('user', ['userInfo']), // 在vuex中查询
    async clickAssignBtn(){
      const permIds =this.$refs.tree.getCheckedKeys()
      await reqAssignPerm({id:this.roleId,permIds})
      this.$message.success('分配权限成功！！！！')
      this.closeShowDia()
      this.getRolePermiss()
    },
    // 分配权限
    async clickAssignPermissions(id) {
      this.DiaShowDia = true
      this.getRolePermiss()
      this.roleId = id
      // 权限的回显
      const {
        data: { permIds },
      } = await reqGetRoleId(id)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    // 获取权限列表转树形数据
    async getRolePermiss() {
      const { data } = await reqGetPermissionList()
      const result = await transListToTree(data, '0')
      this.permissionsData = result
    },
    // 关闭分配列表弹窗
    closeShowDia() {
      this.DiaShowDia = false
      this.$refs.tree.setCheckedKeys([])
    },
    async getComanyInfo() {
      const { data, message } = await reqGetIdCompany(this.userInfo)
      this.$message.success(message)
      this.companyData = data
    },
    // 提交添加
    sumbitBtn() {
      this.$refs.Form.validate(async (flag) => {
        if (!flag) return this.$message.error('校验失败！请重新书写！') // 校验
        this.loading = true
        if (this.form.id) {
          // 根据有无form的id
          // 编辑数据
          const { message, success } = await reqGetUpdataRole(this.form)
          if (!success) return this.$message.error(message)
          this.$message.success(message)
        } else {
          // 添加数据
          const { message, success } = await reqGetAddRoles(this.form) // 解构
          if (!success) this.$message.error(message)
          this.$message.success(message) // 信息提示
        }
        this.loading = false
        this.clickCloseDia() // 关闭弹窗并且清除状态
        this.reqGetRoleList() // 重新刷新数据
      })
    },
    // 触发编辑功能(数据回显)
    async clickShowDia(id) {
      this.showDia = true
      const { data } = await reqGetRoleId(id) // 数据回显
      this.form = data
    },

    // 关闭编辑弹窗

    clickCloseDia() {
      this.showDia = false
      // 关闭重置状态resetFields
      this.$refs.Form.resetFields()
      // 防止清除不完整 resetFields只清除表单里有的内容（你懂得！！！）
      this.form = {
        name: '',
        description: '',
      }
    },

    // 根据作用域插槽获取id删除

    delTable(id) {
      this.$confirm('删除操作不可逆！,是否删除！', '温馨提示')
        .then(async () => {
          const { message, success } = await reqGetDelRole(id)
          if (!success) return
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.$message.success(message)
          // 重新刷新数据
          this.reqGetRoleList()
        })
        .catch(() => {
          this.$message.error('取消删除操作')
        })
    },

    // 序号自定义处理

    typeIndex(index) {
      // console.log(index, '改变的页数')
      return (this.page - 1) * this.pagesize + index + 1
    },

    // 当前页发生改变

    handleCurrentChange(val) {
      this.page = val
      this.reqGetRoleList()
    },

    // 当前页条数发生改变时触发

    handleSizeChange(val) {
      this.pagesize = val // 当前页
      this.page = 1
      // 重新获取数据
      this.reqGetRoleList(this.page, this.pagesize)
    },

    // 获取所有角色信息

    async reqGetRoleList() {
      this.loading = true
      const {
        code,
        data: { rows, total },
        message,
      } = await reqGetSole(this.page, this.pagesize)
      if (!code) return this.$message.error(message)
      this.list = rows
      this.total = total
      this.loading = false
    },
  },
}
</script>

<style>
</style>
